<?php
   namespace app\redis\controller;
   use \think\Controller;
   use \think\Db;
   use \think\Cookie;
   use \think\Log;
   class Index extends Controller{
   private $redis;
   function __construct(){
	   parent::__construct();
      $this->redis=new \redis();
	  $this->redis->connect('localhost',6379);
	  $this->redis->auth('1234');
	  
   } 
      public function index($page=1){
		  $id=$this->redis->get('id');
		  $num=6;
          $key=($page-1)*$num;
          $end=($num-1)*($key+1);
		  $list=[];

		  $userids=$this->redis->lsize('userids');
		  $cont=ceil($userids/$page);

		  $userid=$this->redis->lrange('userids',$key,$key+$num-1);
		   foreach($userid as $k=>$v){
		      $list[$v]=$this->redis->hgetall('user:'.$v);
			  
		   }
		   $list=array_filter($list);
		   $this->assign('list',$list);
           return $this->fetch();
	 }

	 function add($id=''){
		 if($id){
		   $info=$this->redis->hgetall('user:'.$id);
		   $info['id']=$id;
		   $this->assign('info',$info);
		 }
	      return $this->fetch('index/redis_add');
	 }

	 function add_save(){
		 if(input('post.id')!=0){
			 $data=[
			     'username'=>input('post.username'),
				 'age'=>input('post.age'),
				 'sex'=>input('post.sex')
			 ];
		     $res=$this->redis->hmset('user:'.input('post.id'),$data);
		 }else{
	       $id=$this->redis->incr('id');
		   $res=$this->redis->hmset('user:'.$id,input('post.'));
		 }
		if($res){
		  if(input('post.id')!=0){
		     echo '<script>alert("编辑成功");</script>';
		  }else{
		  	 $this->redis->lpush('userids',$id);
		     echo '<script>alert("添加成功");</script>';
		  }
		     
		     echo "<a href='/redis.php/index'>返回列表页</a><br/>";
		    echo "<a href='/redis.php/index/add'>返回</a>";
		}else{
		  echo '<script>alert("添加失败");history.back();</script>';
		}
	 }


function del($id=''){
   if($id){
      $res=$this->redis->del('user:'.$id);
	   if($res){
	   	$this->redis->lrem('userids',$id);
		      echo '<script>alert("删除成功");history.back();parent.location.reload();</script>';
		}else{
		  echo '<script>alert("删除失败");history.back();</script>';
		}
	}
}
   }
?>